import unittest
from functools import wraps
from common.api_request import UrlRequest
from common.logger import *
from common.read_config import *
import os
import sys

# create a logger instance
logger = root_logger.getLogger("root.public_class")


# 开始结束SetupTeardown
class SetupTeardown(unittest.TestCase):
    interfaceapi = {}
    config = {}

    @classmethod
    def setUpClass(cls):
        print("class module 开始测试>>>>>>>>>>>")

    @classmethod
    def tearDownClass(cls):
        print("class module 测试结束>>>>>>>>>>>>\n")

    def setUp(self):
        print("setup begin test")

    def tearDown(self):
        print("teardown test end!")


# 跳过测试用例的装饰器
def skip_dependon(depend=""):
    """
    :param depend: 依赖的用例函数名，默认为空
    :return: wraper_func
    """

    def wraper_func(test_func):
        @wraps(test_func)  # @wraps：避免被装饰函数自身的信息丢失
        def inner_func(self):
            if depend == test_func.__name__:
                raise ValueError("{} cannot depend on itself".format(depend))
            # print("self._outcome", self._outcome.__dict__)
            # 此方法适用于python3.4 +
            # 如果是低版本的python3，请将self._outcome.result修改为self._outcomeForDoCleanups
            # 如果你是python2版本，请将self._outcome.result修改为self._resultForDoCleanups
            failures = str([fail[0] for fail in self._outcome.result.failures])
            errors = str([error[0] for error in self._outcome.result.errors])
            skipped = str([error[0] for error in self._outcome.result.skipped])
            flag = (depend in failures) or (depend in errors) or (depend in skipped)
            if failures.find(depend) != -1:
                # 输出结果 [<__main__.TestDemo testMethod=test_login>]
                # 如果依赖的用例名在failures中，则判定为失败，以下两种情况同理
                # find()方法：查找子字符串，若找到返回从0开始的下标值，若找不到返回 - 1
                test = unittest.skipIf(flag, "{} failed".format(depend))(test_func)
            elif errors.find(depend) != -1:
                test = unittest.skipIf(flag, "{} error".format(depend))(test_func)
            elif skipped.find(depend) != -1:
                test = unittest.skipIf(flag, "{} skipped".format(depend))(test_func)
            else:
                test = test_func
            return test(self)
        return inner_func
    return wraper_func


def get_config_and_userinfo():
    """获取config和用户信息，如果失败退出程序"""

    # 获取config
    config_url = "https://main-globalapi.yyhao.com/app_api/v5/getconfig/?platformname=android&productname=kmh"
    config_result = UrlRequest.url_request(method="get", url=config_url, name="getconfig")
    if config_result["msg"]:  # 获取config接口失败
        logger.critical("config请求失败，请检查main接口是否正确！！")
        # sys.exit()  # 退出程序
        os._exit(0)  # 退出程序

    # 获取config成功
    config = config_result["result"]
    interfaceapi = config["interfaceapi"]

    # login接口获取token
    login_url = con.get_config(section="url_config", key="login_url")
    login_params = {"identity":	con.get_config(section="user_config", key="account"),
                    "pwd": con.get_config(section="user_config", key="password")}
    login_result = UrlRequest.url_request(method="post", url=login_url, data=login_params, name="login获取token")
    if login_result["msg"]:  # 接口失败
        logger.critical("login获取token请求失败，请检查！")
        # sys.exit()  # 退出程序
        os._exit(0)  # 退出程序
    login = login_result["result"]

    # getuserinfo接口
    userinfo_url = interfaceapi["getuserinfo"]
    params = {"token":	login["data"]["appToken"],
              "type": con.get_config(section="user_config", key="login_type")}
    body_data = dict(params, **universalPostData)  # 合并字典
    userinfo_result = UrlRequest.url_request(method="post",
                                             url=userinfo_url,
                                             data=body_data,
                                             name="getuserinfo登录")
    if userinfo_result["msg"]:  # 获取用户信息失败
        logger.critical("getuserinfo请求失败，请检查接口是否正确！！")
        # sys.exit(0)  # 退出程序
        os._exit(0)  # 退出程序
    userinfo = userinfo_result["result"]
    return [config, interfaceapi, userinfo]


def get_novel_interface_api_and_userinfo():
    """"获取小说api"""

    interface_api_url = interfaceapi["novel_interfaceapi"]
    params = {
        "productname": con.get_config(section=app_config_section, key="productname"),
        "platformname": con.get_config(section=app_config_section, key="platformname"),
    }
    novel_api_result = UrlRequest.url_request(method="get", url=interface_api_url, name="novel_api",data=params)
    if novel_api_result["msg"]:  # 获取小说api
        logger.critical("novel interfaceapi请求失败，请检查接口是否正确！！")
        # sys.exit()  # 退出程序
        os._exit(0)  # 退出程序
    interface_api = novel_api_result["result"]["data"]

    """获取小说用户信息"""
    userinfo_url = interface_api["getuserinfo"]
    params = {
        "client-type": con.get_config(section=app_config_section, key="client_type"),
        "productname": con.get_config(section="novel", key="productname"),
        "platformname": con.get_config(section=app_config_section, key="platformname"),
        "client-channel": con.get_config(section=app_config_section, key="client_channel"),
        "client-version": con.get_config(section=app_config_section, key="client_version"),
        "type": con.get_config(section=app_config_section, key="productname"),
        "token":  userinfo["task_data"]["authcode"],
    }
    userinfo_result = UrlRequest.url_request(method="post", url=userinfo_url, name="小说用户信息", data=params)
    if userinfo_result["msg"]:  # 获取小说用户信息
        logger.critical("novel userinfo请求失败，请检查接口是否正确！！")
        # sys.exit()  # 退出程序
        os._exit(0)  # 退出程序
    novel_userinfo = userinfo_result["result"]["data"]
    return [interface_api, novel_userinfo]


app_config_section = "android_app_config"
# 通用组合参数
universalPostData = {
                    "client-type": con.get_config(section=app_config_section, key="client_type"),
                    "productname": con.get_config(section=app_config_section, key="productname"),
                    "platformname": con.get_config(section=app_config_section, key="platformname"),
                    "client-channel": con.get_config(section=app_config_section, key="client_channel"),
                    "client-version": con.get_config(section=app_config_section, key="client_version"),
                    }
universalGetData = {
                    "productname": con.get_config(section=app_config_section, key="productname"),
                    "platformname": con.get_config(section=app_config_section, key="platformname"),
                    }
novel_universalGetData = {
                        "platformname": con.get_config(section=app_config_section, key="platformname"),
                        "productname": con.get_config(section="novel", key="productname"),
                        }
novel_universalPostData = {
                    "client-type": con.get_config(section=app_config_section, key="client_type"),
                    "productname": con.get_config(section="novel", key="productname"),
                    "platformname": con.get_config(section=app_config_section, key="platformname"),
                    "client-channel": con.get_config(section=app_config_section, key="client_channel"),
                    "client-version": con.get_config(section=app_config_section, key="client_version"),
                    }

get_result = get_config_and_userinfo()  # 获取config
config = get_result[0]  # config字典
interfaceapi = get_result[1]  # interfaceapi字典
userinfo = get_result[2]  # 用户信息字典
novel_result = get_novel_interface_api_and_userinfo()  # 小说api字典
novel_interface_api = novel_result[0]    # 小说interfaceapi字典
novel_userinfo = novel_result[1]   # 小说用户信息字典
